package com.jwcao.common.cast.operation.access;

import com.jwcao.common.cast.annotation.CastGet;
import com.jwcao.common.scan.object.ScanClass;
import com.jwcao.common.scan.object.ScanField;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * name: MethodAccessOperationFactory description: TODO
 *
 * @author caojingwei date: 2023/3/24 19:46
 */
public class MethodAccessOperationFactory {

    public static List<MethodAccessOperation> get(String id, ScanClass<?> sourceClass, ScanClass<?> targetClass) {

        return sourceClass.getMethodList().stream()
            .map(method -> {
//                List<CastGet> castGetList = new ArrayList<>();
//                CastGet[] castGets = method.getAnnotationsByType(CastGet.class);
//                if (ArrayUtils.isNotEmpty(castGets)){
//                    castGetList.addAll(List.of(castGets));
//                }
                CastGet[] declareCastGets = method.getDeclaredAnnotationsByType(CastGet.class);
//                if (ArrayUtils.isNotEmpty(declareCastGets)){
//                    castGetList.addAll(List.of(declareCastGets));
//                }

                String fieldName = Arrays.stream(declareCastGets)
                    .filter(c -> StringUtils.equals(c.id(), id))
                    .map(CastGet::value)
                    .map(f -> StringUtils.isNotBlank(f) ? f : method.getName())
                    .findAny().orElse(null);

                // 没有方法名，说明不存在
                if (StringUtils.isBlank(fieldName)){
                    return null;
                }

                ScanField targetField = targetClass.getField(fieldName);
                return new MethodAccessOperation(sourceClass, targetField, method.getName());
            }).filter(Objects::nonNull).collect(Collectors.toList());
    }
}
